package com.hzncc.scaffold.controller.Rear.OnePlusX;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Bo.ExamineeBo;
import com.hzncc.scaffold.entity.Bo.InvigilatorListBo;
import com.hzncc.scaffold.entity.Bo.QuestionReaderBo;
import com.hzncc.scaffold.entity.Other.*;
import com.hzncc.scaffold.entity.Vo.*;
import com.hzncc.scaffold.mapper.ExamineeapplyMapper;
import com.hzncc.scaffold.mapper.OneplusxexamMapper;
import com.hzncc.scaffold.mapper.UserMapper;
import com.hzncc.scaffold.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: DrunkBear
 * @Date: 2022-05-24 16:14
 * @Description: null
 */
@Api(tags = "1+X管理-考务管理")
@RestController
@RequestMapping("/manage/onePlusXExam")
public class ExamManagementController {
    @Autowired
    OneplusxexamService oneplusxexamService;

    @Autowired
    SkillService skillService;

    @Autowired
    ProfessionService professionService;

    @Autowired
    UserService userService;

    @Autowired
    ExamineeapplyService examineeapplyService;

    @Autowired
    InvigilatorconfirmService invigilatorconfirmService;

    @Autowired
    ExamineeapplyMapper examineeapplyMapper;

    @Autowired
    UserMapper userMapper;

    @GetMapping("/list")
    @ApiOperation("考务管理列表")
    public ResultT list(Integer pageNum, Integer pageSize, Integer professionId, Integer status, String keyword) {

        ArrayList<ExamManagementListVo> examManagementListVos = new ArrayList<>();

        LambdaQueryWrapper<Oneplusxexam> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotEmpty(keyword), Oneplusxexam::getTitle, keyword);
        lqw.eq(professionId != null, Oneplusxexam::getProfessionId, professionId);
        lqw.eq(status != null, Oneplusxexam::getStatus, status);
        lqw.orderByDesc(Oneplusxexam::getId);
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Oneplusxexam> oneplusxexamList = oneplusxexamService.list(lqw);

        for (Oneplusxexam oneplusxexam : oneplusxexamList) {

            ExamManagementListVo examManagementListVo = BeanUtil.toBean(oneplusxexam, ExamManagementListVo.class);

            Skill skill = new Skill();
            if (skillService.getById(oneplusxexam.getSkillId()) != null) {
                skill = skillService.getById(oneplusxexam.getSkillId());
            }

            Profession profession = new Profession();
            if (professionService.getById(oneplusxexam.getProfessionId()) != null) {
                profession = professionService.getById(oneplusxexam.getProfessionId());
            }

            CreatorVo creator = new CreatorVo();
            if (userService.getById(oneplusxexam.getCreatorId()) != null) {
                User user = userService.getById(oneplusxexam.getCreatorId());
                creator.setId(user.getId());
                creator.setName(user.getName());
            }

            Integer examineeCount = 0;
            LambdaQueryWrapper<Examineeapply> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Examineeapply::getExamId, oneplusxexam.getId());
            lqww.eq(Examineeapply::getFinalCheck, 1);
            if (examineeapplyService.list(lqww) != null) {
                examineeCount = examineeapplyService.count(lqww);
            }

            ArrayList<InvigilatorConfirmsVo> invigilatorConfirmsVos = new ArrayList<>();
            LambdaQueryWrapper<Invigilatorconfirm> lqwww = new LambdaQueryWrapper<>();
            lqwww.eq(Invigilatorconfirm::getExamId, oneplusxexam.getId());
            lqwww.eq(Invigilatorconfirm::getStatus, 1);
            List<Invigilatorconfirm> invigilatorconfirmList = invigilatorconfirmService.list(lqwww);
            for (Invigilatorconfirm invigilatorconfirm : invigilatorconfirmList) {
                InvigilatorConfirmsVo invigilatorConfirmsVo = BeanUtil.toBean(invigilatorconfirm, InvigilatorConfirmsVo.class);
                invigilatorConfirmsVos.add(invigilatorConfirmsVo);
            }

            examManagementListVo.setInvigilatorConfirms(invigilatorConfirmsVos);
            examManagementListVo.setExamineeCount(examineeCount);
            examManagementListVo.setCreator(creator);
            examManagementListVo.setProfession(profession);
            examManagementListVo.setSkill(skill);
            examManagementListVo.setType(0);
            examManagementListVos.add(examManagementListVo);
        }

//        PageInfo<ExamManagementListVo> info = new PageInfo<>();
//        info.setList(examManagementListVos);
//        info.setTotal(new PageInfo<>(oneplusxexamList).getTotal());

        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",examManagementListVos);
        map.put("count",new PageInfo<>(oneplusxexamList).getTotal());
        return ResultT.success(map);
    }


    @GetMapping("/detail")
    @ApiOperation("考务管理详情")
    public ResultT detail(String examId) {

        ArrayList<ExamManagementListVo> examManagementListVos = new ArrayList<>();

        LambdaQueryWrapper<Oneplusxexam> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Oneplusxexam::getId, examId);
        List<Oneplusxexam> oneplusxexamList = oneplusxexamService.list(lqw);

        for (Oneplusxexam oneplusxexam : oneplusxexamList) {


            ExamManagementListVo examManagementListVo = BeanUtil.toBean(oneplusxexam, ExamManagementListVo.class);

            Skill skill = new Skill();
            if (skillService.getById(oneplusxexam.getSkillId()) != null) {
                skill = skillService.getById(oneplusxexam.getSkillId());
            }

            Profession profession = new Profession();
            if (professionService.getById(oneplusxexam.getProfessionId()) != null) {
                profession = professionService.getById(oneplusxexam.getProfessionId());
            }

            CreatorVo creator = new CreatorVo();
            if (userService.getById(oneplusxexam.getCreatorId()) != null) {
                User user = userService.getById(oneplusxexam.getCreatorId());
                creator.setId(user.getId());
                creator.setName(user.getName());
            }

            Integer examineeCount = 0;
            LambdaQueryWrapper<Examineeapply> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Examineeapply::getExamId, oneplusxexam.getId());
            lqww.eq(Examineeapply::getFinalCheck, 1);
            if (examineeapplyService.list(lqww) != null) {
                examineeCount = examineeapplyService.count(lqww);
            }

            ArrayList<InvigilatorConfirmsVo> invigilatorConfirmsVos = new ArrayList<>();
            LambdaQueryWrapper<Invigilatorconfirm> lqwww = new LambdaQueryWrapper<>();
            lqwww.eq(Invigilatorconfirm::getExamId, oneplusxexam.getId());
            List<Invigilatorconfirm> invigilatorconfirmList = invigilatorconfirmService.list(lqwww);
            for (Invigilatorconfirm invigilatorconfirm : invigilatorconfirmList) {
                InvigilatorConfirmsVo invigilatorConfirmsVo = BeanUtil.toBean(invigilatorconfirm, InvigilatorConfirmsVo.class);
                invigilatorConfirmsVos.add(invigilatorConfirmsVo);
            }

            examManagementListVo.setInvigilatorConfirms(invigilatorConfirmsVos);
            examManagementListVo.setExamineeCount(examineeCount);
            examManagementListVo.setCreator(creator);
            examManagementListVo.setProfession(profession);
            examManagementListVo.setSkill(skill);
            examManagementListVos.add(examManagementListVo);
        }
        return ResultT.success(examManagementListVos);
    }


    @PostMapping("/deleteExam")
    @ApiOperation("删除考试计划")
    public ResultT deleteExam(@RequestBody ExamIdVo examIdVo) {

        String examId = examIdVo.getExamId();

        if (oneplusxexamService.getById(examId) == null) {
            return ResultT.fail("数据错误");
        }

        boolean remove = oneplusxexamService.removeById(examId);
        if (remove) {
            return ResultT.success("删除成功");
        } else {
            return ResultT.fail("删除失败");
        }
    }

    @PostMapping("/addExam")
    @ApiOperation("新增考试计划")
    public ResultT addExam(@RequestBody Oneplusxexam oneplusxexam) {

        oneplusxexam.setCreateTime(DateUtil.now());
        oneplusxexam.setCreatorId(StpUtil.getLoginIdAsInt());
        oneplusxexam.setId(IdUtil.randomUUID());
        boolean save = oneplusxexamService.save(oneplusxexam);
        if (save) {
            return ResultT.success("新增成功");
        } else {
            return ResultT.fail("新增失败");
        }
    }

    @PostMapping("/update")
    @ApiOperation("修改考试计划")
    public ResultT update(@RequestBody UpdateExamVo updateExamVo) {
        if (oneplusxexamService.getById(updateExamVo.getExamId()) == null) {
            return ResultT.fail("数据错误");
        }
        Oneplusxexam oneplusxexam = BeanUtil.toBean(updateExamVo, Oneplusxexam.class);
        oneplusxexam.setId(updateExamVo.getExamId());

        boolean update = oneplusxexamService.updateById(oneplusxexam);

        if (update) {
            return ResultT.success("修改成功");
        } else {
            return ResultT.fail("修改失败");
        }
    }

    @GetMapping("/examineeList")
    @ApiOperation("报名查看")
    public ResultT examineeList(Integer pageNum, Integer pageSize, Integer type, String examId, String keyword) {

        ArrayList<ExamineeListVo> examineeListVos = new ArrayList<>();
        QueryWrapper<Examineeapply> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(examId)) {
            qw.eq("examId", examId);
        }
        if (type != null && type == 0) {
            qw.eq("finalCheck", 1);
        }
        if (type != null && type == 1) {
            qw.eq("finalCheck", 0);
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("realname", keyword);
        }
        qw.orderByDesc("id");
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<ExamineeBo> examineeapplyList = examineeapplyMapper.listBo(qw);

        if (CollUtil.isNotEmpty(examineeapplyList)) {
            for (ExamineeBo examineeapply : examineeapplyList) {
                ExamineeListVo examineeListVo = BeanUtil.toBean(examineeapply, ExamineeListVo.class);

                User creator = new User();
                OneplusxexamVo oneplusxexam = new OneplusxexamVo();

                if (userService.getById(examineeapply.getUserId()) != null) {
                    creator = userService.getById(examineeapply.getUserId());
                }

                if (oneplusxexamService.getById(examineeapply.getId()) != null) {
                    Oneplusxexam one = oneplusxexamService.getById(examineeapply.getId());
                    oneplusxexam = BeanUtil.toBean(one, OneplusxexamVo.class);
                }

                examineeListVo.setCreator(creator);
                examineeListVo.setOneplusxexam(oneplusxexam);
                examineeListVos.add(examineeListVo);
            }
        }
        PageInfo<ExamineeListVo> info = new PageInfo<>();
        info.setList(examineeListVos);
        info.setTotal(new PageInfo<>(examineeapplyList).getTotal());

        return ResultT.success(info);
    }


    @PostMapping("/updateExaminee")
    @ApiOperation("修改待审核考生信息")
    public ResultT updateExaminee(@RequestBody UpdateExamineeVo updateExamineeVo) {
        if (examineeapplyService.getById(updateExamineeVo.getExamineeId()) == null) {
            return ResultT.fail("数据错误");
        }
        Examineeapply examineeapply = examineeapplyService.getById(updateExamineeVo.getExamineeId());
        if (updateExamineeVo.getFinalCheck() != null) {
            examineeapply.setFinalCheck(updateExamineeVo.getFinalCheck());
            examineeapplyService.updateById(examineeapply);
        }
        Integer userId = examineeapply.getUserId();
        User user = BeanUtil.toBean(updateExamineeVo, User.class);
        user.setId(userId);
        boolean update = userService.updateById(user);
        if (update) {
            return ResultT.success("修改成功");
        } else {
            return ResultT.fail("修改失败");
        }
    }

    @PostMapping("/deleteExaminee")
    @ApiOperation("删除考生")
    public ResultT deleteExaminee(@RequestBody ExamineeIdVo examineeIdVo) {

        Integer examineeId = examineeIdVo.getExamineeId();

        if (examineeapplyService.getById(examineeId) == null) {
            return ResultT.fail("数据错误");
        }

        boolean remove = examineeapplyService.removeById(examineeId);
        if (remove) {
            return ResultT.success("删除成功");
        } else {
            return ResultT.fail("删除失败");
        }
    }


    @GetMapping("/invigilatorList")
    @ApiOperation("获取所有的考评员列表")
    public ResultT invigilatorList(Integer pageNum, Integer pageSize, Integer type) {
        String tagName = "";
        if (type == 0) {
            tagName = "专家";
        }

        if (type == 1) {
            tagName = "考核师";
        }

        if (type == 2) {
            tagName = "培训师";
        }

        if (type == 3) {
            tagName = "考务人员";
        }
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<InvigilatorListBo> invigilatorListBos = userMapper.invigilatorList(tagName);
        ArrayList<InvigilatorListVo> invigilatorListVos = new ArrayList<>();

        for (InvigilatorListBo invigilatorListBo : invigilatorListBos) {
            InvigilatorListVo invigilatorListVo = new InvigilatorListVo();

            invigilatorListVo.setRealname(invigilatorListBo.getRealname());
            invigilatorListVo.setTitle(invigilatorListBo.getTagsName());
            invigilatorListVo.setUserId(invigilatorListBo.getId());

            invigilatorListVos.add(invigilatorListVo);
        }

        PageInfo<InvigilatorListVo> info = new PageInfo<>();
        info.setList(invigilatorListVos);
        info.setTotal(new PageInfo<>(invigilatorListBos).getTotal());

        return ResultT.success(info);
    }

    @PostMapping("/addInvigilator")
    @ApiOperation("添加考评员")
    public ResultT addInvigilator(@RequestBody AddInvigilatorVo addInvigilatorVo) {
        List<InvigilatorListVo> invigilator = addInvigilatorVo.getInvigilator();

        for (InvigilatorListVo invigilatorListVo : invigilator) {
            Invigilatorconfirm invigilatorconfirm = new Invigilatorconfirm();
            invigilatorconfirm.setUserId(invigilatorListVo.getUserId());
            invigilatorconfirm.setTitle(invigilatorListVo.getTitle());
            invigilatorconfirm.setExamId(addInvigilatorVo.getExamId());
            invigilatorconfirm.setType(Integer.parseInt(addInvigilatorVo.getType()));
            invigilatorconfirm.setRealname(invigilatorListVo.getRealname());
            invigilatorconfirm.setCreateTime(DateUtil.formatDateTime(new Date()));
            invigilatorconfirmService.save(invigilatorconfirm);
        }

        return ResultT.success("添加成功");
    }


    @PostMapping("/deleteInvigilator")
    @ApiOperation("删除考评员")
    public ResultT deleteInvigilator(@RequestBody InvigilatorIdVo invigilatorIdVo) {
        Integer invigilatorId = invigilatorIdVo.getInvigilatorId();

        boolean remove = invigilatorconfirmService.removeById(invigilatorId);

        if (remove) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }


    @GetMapping("/exportExaminee")
    @ApiOperation("导出考生列表")
    public void exportExaminee(String examId,HttpServletResponse response) throws IOException {
//        @RequestBody ExamIdVo examIdVo,
        ArrayList<ExamineeListVo> examineeListVos = new ArrayList<>();
        QueryWrapper<Examineeapply> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(examId)) {
            qw.eq("examId", examId);
            qw.eq("user.isDelete", false);
            qw.eq("finalCheck", 1);
        }

        List<ExamineeBo> examineeapplyList = examineeapplyMapper.listBo(qw);


//        ArrayList<ExportExamineeVo> exportExamineeVos = new ArrayList<>();
        ArrayList<Map<String, Object>> exportExamineeVos = new ArrayList<>();

        for (ExamineeBo examineeBo : examineeapplyList) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();

            User user = userService.getById(examineeBo.getUserId());

            map.put("真实姓名", user.getRealname());
            map.put("性别", user.getGender());
            map.put("身份证号", user.getIdCardNum());
            map.put("联系方式", user.getTelephone());
            map.put("所属院校", user.getInstituteName());
            map.put("专业", user.getMajor());
            map.put("考试名称", oneplusxexamService.getById(examineeBo.getExamId()).getTitle());
            exportExamineeVos.add(map);
        }

        if (CollUtil.isNotEmpty(exportExamineeVos)) {

            ExcelWriter writer = ExcelUtil.getWriter();
            writer.write(exportExamineeVos, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode("考生列表", "UTF-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
            writer.close();
        }

    }

    @Autowired
    OneplusxexamMapper oneplusxexamMapper;

    @PostMapping("/importExaminee")
    @ApiOperation("导出考生列表")
    public ResultT importExaminee(@RequestParam("file") MultipartFile file, String examId) throws IOException {
        InputStream inputStream = file.getInputStream();

        try {
            ExcelReader excelReader = ExcelUtil.getReader(inputStream);
            excelReader.addHeaderAlias("序号", "id");
            excelReader.addHeaderAlias("姓名", "userName");
            excelReader.addHeaderAlias("性别", "sex");
            excelReader.addHeaderAlias("身份证号码", "idCardNum");
            excelReader.addHeaderAlias("所属院校", "instituteName");
            excelReader.addHeaderAlias("所属专业", "major");
            List<ExamineeBo> examineeBos = excelReader.readAll(ExamineeBo.class);

            for (ExamineeBo examineeBo : examineeBos) {

                QueryWrapper<User> userWrapper = new QueryWrapper<>();
                userWrapper.eq("idCardNum",examineeBo.getIdCardNum());
                userWrapper.eq("name",examineeBo.getUserName());
                userWrapper.eq("role","学生");
                List<PersonalUserVo> personalUserVos = userMapper.listVo(userWrapper);

                if(CollUtil.isEmpty(personalUserVos)){
                    AddUserVo addUserVo = new AddUserVo();
                    addUserVo.setGender(examineeBo.getSex());
                    addUserVo.setIdCardNum(examineeBo.getIdCardNum());
                    addUserVo.setInstituteName(examineeBo.getInstituteName());
                    addUserVo.setMajor(examineeBo.getMajor());
                    addUserVo.setRealname(examineeBo.getUserName());
                    addUserVo.setType(1);
                    userService.addUserNoPhone(addUserVo);
                    personalUserVos = userMapper.listVo(userWrapper);
                }

                Examineeapply examineeapply = new Examineeapply();
                examineeapply.setExamId(examId);
                examineeapply.setCreateTime(DateUtil.formatDateTime(new Date()));
                examineeapply.setFinalCheck(1);
                examineeapply.setFirstCheck(0);
                examineeapply.setUserId(personalUserVos.get(0).getId());
                examineeapply.setIsCommitted(true);
                examineeapplyMapper.insert(examineeapply);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return ResultT.fail("操作失败");
        }
        return ResultT.success("操作成功");


    }
}
